from sqlalchemy import create_engine
from tkinter import *
import pandas as pd
win = Tk()
win.title('xlsx导入mysql工具')
win.geometry('300x400+500+250')
txt1 = Listbox(win)
txt1.insert(0,'导入的文件后缀为xlsx，数据库必须是MySQL')
txt2 = Label(win,text="数据库地址：")
txt3 = Label(win,text="端口号：")
txt4 = Label(win,text="用户名：")
txt5 = Label(win,text="密码：")
txt6 = Label(win,text="数据库：")
txt7 = Label(win,text="excel路径：")
txt8 = Label(win,text="创建的数据表名：").grid(row=7,column=0)
dizi = Entry(win)#数据库地址
port = Entry(win)#数据库端口号
user = Entry(win)#数据库账号
password = Entry(win)#数据库密码
sqll = Entry(win)#数据库
file = Entry(win)#文件
sjubiao = Entry(win)
sjubiao.grid(row=7,column=1)#创建的数据表名
def mysql():
    print(f"mysql+mysql://{user.get()}:{password.get()}@{dizi.get()}:{port.get()}/{sqll.get()}")
    try:
        db = create_engine(f"mysql+pymysql://{user.get()}:{password.get()}@{dizi.get()}:{port.get()}/{sqll.get()}")

        data = pd.read_excel(file.get())

        data.to_sql(name=sjubiao.get(),con=db,if_exists='append',index=False)
        txt1.insert(0,'导入完成')
    except:
        txt1.insert(0,'导入失败请检查')

ok = Button(win,text='导入',command=mysql)

txt1.grid(row=0,columnspan=2)
dizi.grid(row=1,column=1)
txt2.grid(row=1,column=0)
port.grid(row=2,column=1)
txt3.grid(row=2,column=0)
user.grid(row=3,column=1)
txt4.grid(row=3,column=0)
password.grid(row=4,column=1)
txt5.grid(row=4,column=0)
sqll.grid(row=5,column=1)
txt6.grid(row=5,column=0)
file.grid(row=6,column=1)
txt7.grid(row=6,column=0)
ok.grid(row=8,columnspan=2)

win.mainloop()